"use client";
import { getTemplate } from "@/app/templates/templates";
import { ResumeResult } from "@/lib/api";
import { handleJsonStream } from "@/lib/json-stream-handler";
import { Resume } from "@/lib/schemas/resume-form";
import { useMemoizedFn } from "ahooks";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import ResumeAIDialog from "./resume-ai-dialog";
import ResumeForm, { ResumeFormRef } from "./resume-form";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { dropdownOptions, platformCodes } from "../constants";
import { AiResumeTranslatePrompt } from "@/lib/system-prompt";
import { useStreamData } from "@/hooks/use-stream-data";
import ResumeTemplateDialog from "./resume-template-dialog";
import { toast } from "sonner";
import { ScrollArea } from "@/components/ui/scroll-area";

export default function ResumeEditor({
  value: { jsonString, remarks },
}: {
  value: Pick<ResumeResult, "jsonString" | "remarks">;
}) {
  const resumeValue = JSON.parse(jsonString);
  const [resume, setResume] = useState<Resume>(resumeValue);

  const [templateCode, setTemplateCode] = useState(remarks ?? "Template01");
  const { component: TemplateComponent } = getTemplate(templateCode);
  const [showAIDialog, setShowAIDialog] = useState(false);
  const [showTemplateDialog, setShowTemplateDialog] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const formRef = useRef<ResumeFormRef | null>(null);
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const { data, chat } = useStreamData(platformCodes[0]);

  const router = useRouter();

  // useEffect(() => {
  //     formRef.current?.reset(resume);
  // }, [resume])

  useEffect(() => {
    if (data) {
      const newResumeData = handleJsonStream(resume, data);
      setResume(newResumeData);
      formRef.current?.reset(newResumeData);
    }
  }, [data]);

  const reset = () => {
    const newResumeData = {
      title: "",
      primary: "#000000",
      secondary: "#666666",
      basicInfo: {
        title: "基础信息",
        data: [],
      },
      education: {
        title: "教育经历",
        data: [],
      },
      experience: {
        title: "工作经历",
        data: [],
      },
      externals: [],
    };
    setResume(newResumeData);
    formRef.current?.reset(newResumeData);
  };

  const handleAiGenerate = useMemoizedFn((data: string) => {
    const newResumeData = handleJsonStream(resume, data);
    setResume(newResumeData);
    formRef.current?.reset(newResumeData);
  });

  const handleAiTranslate = useMemoizedFn((promptName: string) => {
    chat([
      { role: "system", content: AiResumeTranslatePrompt },
      {
        role: "user",
        content: `帮我把这里边的数据翻译成 ${promptName}，数据如下所示：${JSON.stringify(
          formRef.current?.getValues()
        )}`,
      },
    ]);
  });

  const handleFormChange = useMemoizedFn((value: Resume) => {
    setResume(value);
  });

  // 处理文件上传
  const handleFileUpload = useMemoizedFn(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files?.[0];
      if (!file) return;

      // 检查文件类型
      if (!file.type.startsWith("image/")) {
        toast.error("请选择图片文件（支持 JPG、PNG、GIF 等格式）");
        return;
      }

      // 检查文件大小（限制为5MB）
      if (file.size > 5 * 1024 * 1024) {
        toast.error("图片大小不能超过5MB");
        return;
      }

      setIsUploading(true);

      const reader = new FileReader();
      reader.onload = (e) => {
        const result = e.target?.result as string;
        if (result) {
          // 更新简历数据中的头像
          const newResumeData = { ...resume, avatar: result };
          setResume(newResumeData);
          formRef.current?.reset(newResumeData);
          toast.success("职业照上传成功！");
        }
        setIsUploading(false);
      };

      reader.onerror = () => {
        toast.error("文件读取失败，请重试");
        setIsUploading(false);
      };

      reader.readAsDataURL(file);

      // 清空input值，允许重复选择同一文件
      event.target.value = "";
    }
  );

  // 触发文件选择
  const triggerFileSelect = useMemoizedFn(() => {
    fileInputRef.current?.click();
  });

  return (
    <div className="w-full bg-[#f2f2f2]">
      {/* 隐藏的文件输入框 */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileUpload}
        className="hidden"
      />

      <div className="flex items-center gap-2 p-4 bg-white border-b mb-4 rounded-t">
        <button
          className="px-4 py-1 bg-gray-100 rounded hover:bg-gray-200"
          onClick={() => {
            router.push("/resumes");
          }}
        >
          返回
        </button>
        <button
          className="px-4 py-1 bg-gray-100 rounded hover:bg-gray-200"
          onClick={() => {
            /* 导出事件 */
          }}
        >
          导出
        </button>
        <button
          className={`px-4 py-1 rounded transition-colors ${
            isUploading
              ? "bg-gray-300 cursor-not-allowed"
              : "bg-gray-100 hover:bg-gray-200"
          }`}
          onClick={triggerFileSelect}
          disabled={isUploading}
        >
          {isUploading ? "上传中..." : "上传职业照"}
        </button>
        <button
          className="px-4 py-1 bg-gray-100 rounded hover:bg-gray-200"
          onClick={() => setShowTemplateDialog(true)}
        >
          选择模板
        </button>
        <button
          className="px-4 py-1 bg-blue-500 text-white rounded hover:bg-blue-600"
          onClick={() => setShowAIDialog(true)}
        >
          AI生成
        </button>

        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <button className="px-4 py-1 bg-green-500 text-white rounded hover:bg-green-600">
              AI翻译
            </button>
          </DropdownMenuTrigger>
          <DropdownMenuContent>
            {dropdownOptions.map((item) => (
              <DropdownMenuItem
                onClick={() => handleAiTranslate(item.promptName)}
                key={item.key}
              >
                {item.label}
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        <button
          className="ml-auto px-4 py-1 bg-[#1677ff] text-white rounded hover:bg-blue-700"
          onClick={() => {
            /* 保存事件 */
          }}
        >
          保存
        </button>
        <ResumeAIDialog
          open={showAIDialog}
          onBeforeGenerate={reset}
          onClose={() => setShowAIDialog(false)}
          onGenerate={handleAiGenerate}
        />
        <ResumeTemplateDialog
          open={showTemplateDialog}
          onClose={() => setShowTemplateDialog(false)}
          onSelect={(templateCode) => {
            if (templateCode) {
              setTemplateCode(templateCode);
            }
          }}
        />
      </div>

      <div className="flex gap-4 ">
        <ScrollArea className="h-screen">
          <ResumeForm
            ref={formRef}
            value={resume}
            onChange={handleFormChange}
          />
        </ScrollArea>

        <ScrollArea className="h-screen">
          <TemplateComponent resume={resume} />
        </ScrollArea>
      </div>
    </div>
  );
}
